package LC;

/**
 * @ClassName Lc25
 * @Description: TODO
 * @Author hl
 * @Date 2021/4/8
 * @Version V1.0
 **/
public class Lc25 {
    public ListNode reverseKGroup(ListNode head, int k) {
        ListNode hair = new ListNode(0);
        hair.next = head;
        ListNode pre = hair;

        while (head != null) {
            ListNode tail = pre;
            // 查看剩余部分长度是否大于等于 k
            for (int i = 0; i < k; ++i) {
                tail = tail.next;
                if (tail == null) {
                    return hair.next;
                }
            }
            ListNode nex = tail.next;
            ListNode[] reverse = myReverse(head, tail);
            head = reverse[0];
            tail = reverse[1];
            // 把子链表重新接回原链表
            pre.next = head;
            tail.next = nex;
            pre = tail;
            head = tail.next;
        }

        return hair.next;
    }

    public ListNode[] myReverse(ListNode head, ListNode tail) {//head和tail是不变的，表示头和尾巴
      ListNode pre=tail.next;
      ListNode p=head;
      while(pre!=tail){
          ListNode next=p.next;
          p.next=pre;
          pre=p;
          p=next;//此时不能用p=p.next,因为p.next已经指向了pre
      }
      return new ListNode[]{tail,head};//要将头尾颠倒
    }
}
